/*
 * acooly.cn Inc.
 * Copyright (c) 2016 All Rights Reserved.
 * create by zhangpu 
 * date:2016年3月20日
 *
 */
package com.ouwen.smartpay.service.notify;

import com.fm.common.emuns.MessageType;
import com.fm.common.order.NotifyOrder;
import com.ouwen.smartpay.entity.NotifyMessage;
import com.ouwen.smartpay.service.NotifyMessageSendDispatcher;
import com.ouwen.smartpay.service.NotifyMessageSendHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.EnumMap;
import java.util.Map;

/***
 *@author <a href="http://youngitman.tech">青年IT男</a>
 *@version v1.0.0
 *@className NotifyMessageSendDispatcherImpl
 *@description 异步通知消息分发
 *@JunitTest: {@link  }
 *@date 16:13 2020-04-27
 *
**/
@Component
public class NotifyMessageSendDispatcherImpl implements NotifyMessageSendDispatcher, InitializingBean {

	private static final Logger logger = LoggerFactory.getLogger(NotifyMessageSendDispatcherImpl.class);

	private static Map<MessageType, NotifyMessageSendHandler> handlerMap = new EnumMap<>(MessageType.class);

	@Resource
	private ApplicationContext applicationContext;

	@Override
	public void dispatch(NotifyMessage notifyMessage, NotifyOrder order) {

		NotifyMessageSendHandler handler = handlerMap.get(notifyMessage.getMessageType());

		if (handler == null) {

			throw new RuntimeException(notifyMessage.getMessageType() + "类型的通知发送组件不存在");
		}

		handler.send(notifyMessage,order);
	}

	@Override
	public void afterPropertiesSet() throws Exception {

		Map<String, NotifyMessageSendHandler> map = applicationContext.getBeansOfType(NotifyMessageSendHandler.class);

		if (map.isEmpty()) {

			return;
		}

		for (NotifyMessageSendHandler handler : map.values()) {

			if (handler.getNotifyMessageType() != null) {

				handlerMap.put(handler.getNotifyMessageType(), handler);

				logger.info("加载{}通知发送组件:{}", handler.getNotifyMessageType().getCode(), handler);
			}
		}
	}

}
